//  Home Assistant 地址
const haUrl = "ws://172.20.80.1:8999/api/websocket";
// 访问令牌，用于认证 Home Assistant API
const accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkNjA1OTFlZmQ5ZTg0OTQ2OWMxMTM0ZDJkYjEwYjJiNyIsImlhdCI6MTc1ODE4OTQyNywiZXhwIjoyMDczNTQ5NDI3fQ.27uaWBHzibkpFBfyv37NN1puqwHtRu5bPTuY8z1a0fI";

// 实体ID，用于指定 Home Assistant 中的特定设备或实体
const entityId = "cover.living_room_curtain";


// 实体集合
let entityArray = new Array();


// socket 实际例子
let socket = null;

// 消息ID，用于标识每个发送的消息
let messageId = 1;
// 订阅ID，用于标识当前的订阅
let subscriptionId = null;


// WebSocket相关逻辑（保持不变）
function connectWebSocket() {
    socket = new WebSocket(haUrl);
    socket.onopen = (e) => {

        authenticate();
    };
    socket.onmessage = (e) => {
        handleWebSocketMessage(JSON.parse(e.data));

    };
    socket.onclose = () => setTimeout(connectWebSocket, 5000);
    socket.onerror = () => { };
}


// 处理web socket 消息

function handleWebSocketMessage(message) {


    switch (message.type) {
        case "auth_required":
            authenticate();

            break;
        case "auth_ok":
            subscribeToEvents();
            break;
        case "result":
            if (message.success && message.id === 2) {
                subscriptionId = message.result.id;
                getCurrentState();
            }
            break;
        case "event":
            if (message.event && message.event.event_type === "state_changed") {
                
                console.log("id", message.event.data.entity_id);

                console.log("状态",message.event.data.new_state);
                console.log("entityArray",entityArray);
                
                
                
                lightArray.forEach(eItem => {
                    if (eItem.entity_id === message.event.data.entity_id) {
                        if (message.event.data.new_state.state === 'on') {
                            console.log("添加灯光", eItem.light);
                            
                            scene.add(eItem.light);
                        } else {
                            scene.remove(eItem.light);
                            console.log("移除灯光", eItem.light);
                        }
                    }
                })

                const newState = message.event.data.new_state;
                if (newState && newState.entity_id === entityId) updateUI(newState);
            }
            break;
    }
}


// 授权信息
function authenticate() {

    socket.send(JSON.stringify({ type: "auth", access_token: accessToken }));
    //更新窗帘的动态
    getCurrentState();


}


// 订阅事件信息

function subscribeToEvents() {

    socket.send(JSON.stringify({
        id: messageId++,
        type: "subscribe_events",
        event_type: "state_changed",
    }));
}


// 获取当前状态
function getCurrentState() {
    const id = messageId++;
    socket.send(JSON.stringify({ id, type: "get_states" }));

    const originalOnMessage = socket.onmessage;
    socket.onmessage = (e) => {
        const msg = JSON.parse(e.data);
        // 赋值实体集合
        entityArray = msg?.result || [];

        //更新灯的开关情况
        updateLightToggleFirst();

        if (msg.type === "result" && msg.id === id) {
            if (msg.success) {
                const curtain = msg.result.find((s) => s.entity_id === entityId);

                if (curtain) updateUI(curtain);
            }
            socket.onmessage = originalOnMessage;
        } else originalOnMessage(e);
    };
}

// 刷新后获取窗帘的状态
function updateLightToggleFirst() {

    // 查找对应的实体并且设置是否添加灯光
    lightArray.forEach(lightItem => {
        entityArray.forEach(eItem => {
            if (eItem.entity_id === lightItem.entity_id) {
                if (eItem.state === 'on') {
                    scene.add(lightItem.light);
                } else {
                    scene.remove(lightItem.light);
                }
            }

        })

    })
}






